<!DOCTYPE HTML>
<html>
<head>
  <meta charset="utf-8">
  <title>拖拽</title>
   <style>  #div1{width:100px;height:100px;background:red;position:absolute;}
   #div2{width:400px;height:300px;background:#CCC;position:relative;}
   </style>
   <script>
      window.onload=function(){
	     var oDiv=document.getElementById('div1');
		 var oDiv2=document.getElementById('div2');
		 var disX=0;
		 var disY=0;
		 oDiv.onmousedown=function(ev){
		    var oEvent=ev||event;
			//div的X坐标
			disX=oEvent.clientX-oDiv.offsetLeft;
			//div的Y坐标
			disY=oEvent.clientY-oDiv.offsetTop;	   
			document.onmousemove=function(ev){
		    var oEvent=ev||event;
			//防止拖拽出页面
			var l=oEvent.clientX-disX;
			var t=oEvent.clientY-disY;
			if(l<0){
			    l=0;	
			 }else if(l>oDiv2.offsetWidth-oDiv.offsetWidth){
                l=oDiv2.offsetWidth-oDiv.offsetWidth;		 
			 }
			if(t<0){
			    t=0;
			 }else if(t>oDiv2.offsetHeight-oDiv.offsetHeight){
			 t=oDiv2.offsetHeight-oDiv.offsetHeight;
			 	 		 
			 }
            //设置div的位置		 
			oDiv.style.left=l+'px';
		    oDiv.style.top=t+'px';
		    };
			//鼠标按键松开
			document.onmouseup=function(){
			   document.onmousemove=null;
			   document.onmouseup=null;
			};
			//阻止默认事件，当拖拽到外部的情况下，会有分身
			return false;
		 };	 
	  };  
   </script>
</head>
<body>
 <div id="div2">
  <div id="div1"></div>
 </div>

</body>
</html>